<template>
  <div class="long-report-modal">
    <el-tabs style="width: 100%;overflow: hidden" @tab-change='onChange'
             v-model="state.defaultActiveKey">
      <el-tab-pane label="段时报告" key="1" name="1">
        <div>开始时间：{{ state.time || '' }}</div>
        <div class="analysis">
          <div class="title">报告分析</div>
          <div class="line"><span>恢复能力</span><span>{{ state.resilience }}</span></div>
          <div class="line"><span>平均心率</span><span>{{ state.average }}</span></div>
          <div class="line"><span>自主神经系统</span><span>{{ state.shengjing }}</span></div>
          <div class="line"><span>抗压能力</span><span>{{ state.kangya }}</span></div>
        </div>

        <div class="heart-rate">
          <div id="hr-chart" class="chart" style="width: 100%;">
            <div class="title-div">
              <span class="title">心率曲线图</span>
            </div>
          </div>
        </div>

        <div class="analysis">
          <div class="line"><span>平均心率</span><span>{{ state.average }}</span><span>{{
              state.averageValue
            }}</span></div>
          <div class="line"><span>最高心率</span><span>{{ state.max }}</span><span>{{ state.maxValue }}</span>
          </div>
          <div class="line"><span>最小心率</span><span>{{ state.min }}</span><span>{{ state.minValue }}</span>
          </div>
        </div>
        <div class="group-chart">
          <div id="hrv-group-chart" class="chart" style="width: 100%;">
            <div class="title-div">
              <span class="title">频率组分</span>
            </div>
          </div>
        </div>
        <div class="shengjing-chart">
          <div class="chart" id="hrv-shengjing-chart" style="width: 100%;">
            <div class="title-div">
              <span class="title">交副神经</span>
            </div>
          </div>
        </div>
        <div class="analysis">
          <div class="line"><span>抗压能力</span><span>{{ state.abindex }}</span><span>{{
              state.kangya
            }}</span></div>
          <div class="line"><span>心率变异性</span><span>{{ state.hrv }}</span><span>{{ state.resilience }}</span>
          </div>
          <div class="line"><span>情绪压力</span><span>{{ state.eindex }}</span><span>{{ state.qingxu }}</span>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="长时报告" key="2" name="2">
        <div>开始时间：{{ state.tStartSleep }}</div>
        <div>结束时间：{{ state.tEndSleep }}</div>
        <div>持续时长：{{ state.sleepValue }}</div>
        <div>
          <div id="hr-long-chart" class="chart" style="width: 100%;">
            <div class="title-div">
              <span class="title">心率曲线图</span>
            </div>
          </div>
        </div>
        <div class="analysis">
          <div class="line"><span>平均心率</span><span>{{ state.longs.average }}</span><span>{{
              state.longs.averageValue
            }}</span></div>
          <div class="line"><span>最高心率</span><span>{{ state.longs.max }}</span><span>{{
              state.longs.maxValue
            }}</span></div>
          <div class="line"><span>最小心率</span><span>{{ state.longs.mins }}</span><span>{{
              state.longs.minValue
            }}</span></div>
          <div class="line"><span>基准心率</span><span>{{ state.longs.base }}</span><span>{{
              state.longs.baseValue
            }}</span></div>
        </div>
        <div class="sdann-pnn50">
          <div id="hr-sdann-chart" style="width: 100%;">
            <div class="title-div">
              <span class="title">sdann</span>
            </div>
            <span class="chat-value">{{ state.hrvData.hrvTimeDomain.sDANN.replace(',', ' ') }}</span>
          </div>
          <div id="hr-pNN50-chart" style="width: 100%;">
            <div class="title-div">
              <span class="title">pNN50</span>
            </div>
            <span class="chat-value">{{ state.hrvData.hrvTimeDomain.pNNx.replace(',', ' ') }}</span>
          </div>
        </div>
        <div>
          <div id="hr-bpmn-chart" class="chart" style="width: 100%;">
            <div class="title-div">
              <span class="title">bpmn</span>
            </div>
          </div>
        </div>
        <div>
          <div id="hr-ibix-chart" class="chart" style="width: 100%;">
            <div class="title-div">
              <span class="title">ibix</span>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import {defineProps, nextTick, onMounted, reactive, watch} from 'vue';

import moment from 'moment';
import * as echarts from 'echarts';

import {findHrvBySleepResultIdApi} from '@/api/sleep';

const props = defineProps({
  hrvData: {
    type: Object,
  },
});
let state = reactive({
  sdannPlot: null as any,
  defaultActiveKey: '1' as any,
  hrvData: {
    hrvTimeDomain: {
      sDANN: '',
      pNNx: ''
    },
  } as any,
  abindex: null as any,
  averageValue: null as any,
  resilience: '' as any,
  time: '' as any,
  average: null as any,
  shengjing: null as any,
  qingxu: null as any,
  kangya: null as any,
  max: null as any,
  maxValue: null as any,
  min: null as any,
  minValue: null as any,
  eindex: null as any,
  hrv: null as any,
  tStartSleep: null as any,
  tEndSleep: null as any,
  sleepValue: null as any,
  longs: {} as any
});
onMounted(() => {
  nextTick(() => {
    init(props.hrvData);
  })
});
watch(
    () => props.hrvData,
    (v) => {
      nextTick(() => {
        init(v);
      })
    },
    {deep: true},
);
const onChange = (key: string) => {
  state.defaultActiveKey = key
  window.setTimeout(() => {
    if (key === '1') {
      initChart(state.hrvData, 'hr-chart');
      shortTime(state.hrvData)
    } else {
      initChart(state.hrvData, 'hr-long-chart');
      longTime(state.hrvData)
      initLongChart(state.hrvData, 'hr-bpmn-chart')
      initLongChart(state.hrvData, 'hr-ibix-chart')
    }
  }, 500)
}
/**
 * 初始化函数
 * */
const init = async (hrvData: any) => {
  await findHrvBySleepResultIdApi({
    iSleepResultId: hrvData?.iSleepResultId || '',
  }).then((r) => {
    state.hrvData = r
    initChart(r, 'hr-chart');
    initGroup(r, 'hrv-group-chart');
    initJiaoFu(r, 'hrv-shengjing-chart');
    shortTime(r)
  });
  // debugger
}
const initLongChart = async (r: any, id: any) => {
  let dataY = id === 'hr-ibix-chart' ? r.hrvTimeDomain.ibin || [] : r.hrvTimeDomain.bpmn || []
  let dataX = id === 'hr-ibix-chart' ? r.hrvTimeDomain.ibix || [] : r.hrvTimeDomain.bpmx || []
  let title = id === 'hr-ibix-chart' ? 'ibix' : 'bpmn'
  let chartData = {
    title: {
      text: title,
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: dataX.split(','),
        axisTick: {
          alignWithLabel: false,
          show: false
        },
        axisLabel: {show: false},
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        name: 'Direct',
        type: 'bar',
        barWidth: '60%',
        data: dataY.split(',')
      }
    ]
  }
  // 绘制图表
  initChartData(chartData, id);
}
const longTime = async (r: any) => {
  state.tStartSleep = r.sleepResult.tStartSleep.replace('T', ' ')
  state.tEndSleep = r.sleepResult.tEndSleep.replace('T', ' ')
  state.sleepValue = ((new Date(state.tEndSleep).getTime() - new Date(state.tStartSleep).getTime()) / 1000 / 60 / 60).toFixed(1) + '时'
  state.longs.average = r.hrvHeartRate.mean || 0
  if (state.longs.average > 90) {
    state.longs.averageValue = '心动过速'
  } else if (state.longs.average > 50) {
    state.longs.averageValue = '心动正常'
  } else {
    state.longs.averageValue = '心动过缓'
  }
  state.longs.max = r.hrvHeartRate.max || 0
  if (state.longs.max > 100) {
    state.longs.maxValue = '高'
  } else if (state.longs.max < 60) {
    state.longs.maxValue = '低'
  } else {
    state.longs.maxValue = '正常'
  }
  state.longs.mins = r.hrvHeartRate.min || 0
  if (state.longs.mins > 100) {
    state.longs.minValue = '高'
  } else if (state.longs.mins < 60) {
    state.longs.minValue = '低'
  } else {
    state.longs.minValue = '正常'
  }
  state.longs.base = r.hrvHeartRate.base || 0
  if (state.longs.base > 70) {
    state.longs.baseValue = '较高'
  } else if (state.longs.base >= 55 && state.longs.base <= 65) {
    state.longs.baseValue = '良好'
  } else if (state.longs.base < 43) {
    state.longs.baseValue = '低'
  }
}
const shortTime = async (r: any) => {
  state.time = r.hrvTimeDomain5.time.replace('T', ' ')
  // 心率变异性
  const domain5Hrv = r.hrvTimeDomain5.hrv || 0
  state.hrv = domain5Hrv
  if (domain5Hrv >= 0.8) {
    state.resilience = '较好'
  } else if (domain5Hrv >= 0.5) {
    state.resilience = '正常'
  } else {
    state.resilience = '较弱'
  }
  // 抗压能力
  const domain5abindex = r.hrvTimeDomain5.abindex || 0
  state.abindex = domain5abindex
  if (domain5abindex >= 0.8) {
    state.kangya = '强'
  } else if (domain5abindex >= 0.5) {
    state.kangya = '正常'
  } else {
    state.kangya = '弱'
  }
  // 平均心率
  state.average = parseInt(r.hrvHeartRate5.mean)
  if (state.average > 90) {
    state.averageValue = '心动过速'
  } else if (state.average >= 50) {
    state.averageValue = '心动正常'
  } else {
    state.averageValue = '心动过缓'
  }
  // 情绪压力
  state.eindex = r.hrvFreqDomain5.eindex
  if (state.eindex > 0.8) {
    state.qingxu = '高'
  } else if (state.eindex >= 0.5) {
    state.qingxu = '正常'
  } else {
    state.qingxu = '弱'
  }
  let hrvTimeDomain5nLf = r.hrvFreqDomain5.nLF
  let hrvTimeDomain5nHf = r.hrvFreqDomain5.nHF
  let value = hrvTimeDomain5nLf / hrvTimeDomain5nHf
  if (value > 2.0) {
    state.shengjing = '交感(SNS)强势'
  } else if (value >= 1.5) {
    state.shengjing = '自主神经系统良好'
  } else {
    state.shengjing = '副交感(PNS)强势'
  }
  state.max = r.hrvHeartRate5.max
  if (state.max > 100) {
    state.maxValue = '高'
  } else if (state.max < 60) {
    state.maxValue = '低'
  } else {
    state.maxValue = '正常'
  }
  state.min = r.hrvHeartRate5.min
  if (state.min > 100) {
    state.minValue = '高'
  } else if (state.min < 60) {
    state.minValue = '低'
  } else {
    state.minValue = '正常'
  }

}
const initJiaoFu = async (_data: any, id: any) => {
  let chartData = {
    title: {
      text: '交副神经',
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (dataArray: any) {
        // eslint-disable-next-line one-var
        let hr = '-' as any,
            time = '-' as any;
        if (dataArray) {
          time =
              dataArray[0] && dataArray[0].axisValue
                  ? dataArray[0].axisValue.replace('\n', ' ')
                  : '-';
          hr = dataArray[0] && dataArray[0].data ? parseFloat(dataArray[0].data) : '-';
        }
        return (time + '：' + hr);
      },
    },
    xAxis: {
      type: 'category',
      data: ['交敢', '副交敢']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        barWidth: 30,//柱图宽度
        data: [_data.hrvFreqDomain5.nLF, _data.hrvFreqDomain5.nHF],
        type: 'bar',
        itemStyle: {
          normal: {
            label: {
              show: true, //开启显示
              position: 'top', //在上方显示
              textStyle: { //数值样式
                color: 'black',
                fontSize: 16
              }
            }
          }
        }
      }
    ]
  };
  // 绘制图表
  initChartData(chartData, id);
}
const initGroup = async (_data: any, id: any) => {
  let chartData = {
    title: {
      text: '频率组分',
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (dataArray: any) {
        // eslint-disable-next-line one-var
        let hr = '-' as any,
            time = '-' as any;
        if (dataArray) {
          time =
              dataArray[0] && dataArray[0].axisValue
                  ? dataArray[0].axisValue.replace('\n', ' ')
                  : '-';
          hr = dataArray[0] && dataArray[0].data ? parseInt(dataArray[0].data) : '-';
        }
        return (time + '：' + hr);
      },
    },
    xAxis: {
      type: 'category',
      data: ['TP', 'VLF', 'LF', 'HF']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        barWidth: 30,//柱图宽度
        data: [_data.hrvFreqDomain5.aTotal, _data.hrvFreqDomain5.aVLF, _data.hrvFreqDomain5.aLF, _data.hrvFreqDomain5.aHF],
        type: 'bar',
        itemStyle: {
          normal: {
            label: {
              show: true, //开启显示
              position: 'top', //在上方显示
              textStyle: { //数值样式
                color: 'black',
                fontSize: 16
              }
            }
          }
        }
      }
    ]
  };
  // 绘制图表
  initChartData(chartData, id);
}
const initChart = async (_data: any, id: any) => {
  const data = [] as any;
  const mtHrCurveArr = [] as any;
  const _tStartSleep = moment(_data?.sleepResult?.tStartSleep).valueOf();
  let hrMax = 0
  let hrMin = 0
  let heartRate = id === 'hr-chart' ? _data.hrvHeartRate5.hr || '' : _data.hrvHeartRate.hr || '';
  heartRate.split(',').forEach((num: any, _index: any) => {
    const _num = parseFloat(num || 0);
    if (!isNaN(_num)) {
      let longTime = new Date(_tStartSleep).setSeconds(_index * 30);
      const longTimeFormat = moment(longTime).format('MM/DD hh:mm:ss');
      data.push(longTimeFormat);
      mtHrCurveArr.push(_num)
      if (!hrMax || hrMax < _num) {
        hrMax = _num
      }
      if (!hrMin || hrMin < _num) {
        hrMin = _num
      }
    }
  });

  let chartData = {
    title: {
      text: '心率曲线图',
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (dataArray: any) {
        // eslint-disable-next-line one-var
        let hr = '-' as any,
            time = '-' as any;
        if (dataArray) {
          time =
              dataArray[0] && dataArray[0].axisValue
                  ? dataArray[0].axisValue.replace('\n', ' ')
                  : '-';
          hr = dataArray[0] && dataArray[0].data ? parseInt(dataArray[0].data) : '-';
        }
        return (
            '时间：' + time + '<br/>' + '心率：' + hr
        );
      },
    },
    legend: {
      data: ['心率'],
    },
    grid: {
      y2: 80,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      axisLine: {onZero: false},
      data: data,
      axisLabel: {
        interval: data.length / 50,
        rotate: 60,
      },
    },
    yAxis: [
      {
        type: 'value',
        name: '心率(次/每分)',
        min: 1,
        max: hrMax,
        axisLabel: {
          formatter: '{value} ',
        },
      },
      {
        type: 'value',
        name: '呼吸(次/每分)',
        min: 1,
        max: hrMin,
        axisLabel: {
          formatter: '{value} ',
        },
      },
    ],
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 20,
        zoomLock: true,
      },
      {
        start: 0,
        end: 20,
        zoomLock: true,
      },
    ],
    series: [
      {
        name: '心率',
        type: 'line',
        smooth: true,
        data: mtHrCurveArr,
        color: ['#DB9B5C'],
        markPoint: {
          data: [
            {type: 'max', name: '最大值'},
            {type: 'min', name: '最小值'},
          ],
        },
        markLine: {
          data: [{type: 'average', name: '平均值'}],
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(191,91,22,0.8)',
            },
            {
              offset: 1,
              color: 'rgba(255,229,212,0.3)',
            },
          ]),
        },
      }
    ],
  }
  // 绘制图表
  initChartData(chartData, id);
};

const initChartData = async (options: any, id: any) => {
  // 基于准备好的dom，初始化echarts实例
  let myChart = echarts.init(document.getElementById(id), id);
  // eslint-disable-next-line no-unused-vars
  // 绘制图表
  myChart.setOption(options)
}
</script>